package com.clstu.reflection;

import java.util.*;
import java.lang.reflect.*;

/**
 * 演示动态加载和静态加载的区别,以及类加载中的锁机制
 */
public class ClassLoad_{
    public static void  main(String[] args) throws Exception{
        /*
        protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException
        {
            synchronized (getClassLoadingLock(name)) {  //类加载的时候值只成一个它的class对象的原因就在这
                                                        //通过互斥锁实现的,只有一个线程能够加载这个类,后面的线程就不能加载了,直接使用
                                                        //加载好的class对象就行了
                // First, check if the class has already been loaded
                Class<?> c = findLoadedClass(name);
                if (c == null) {
                    long t0 = System.nanoTime();
                    try {
                        if (parent != null) {
                            c = parent.loadClass(name, false);
                        } else {
                            c = findBootstrapClassOrNull(name);
                        }
                    } catch (ClassNotFoundException e) {
                        // ClassNotFoundException thrown if class not found
                        // from the non-null parent class loader
                    }

                    if (c == null) {
                        // If still not found, then invoke findClass in order
                        // to find the class.
                        long t1 = System.nanoTime();
                        c = findClass(name);

                        // this is the defining class loader; record the stats
                        sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                        sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                        sun.misc.PerfCounter.getFindClasses().increment();
                    }
                }
                if (resolve) {
                    resolveClass(c);
                }
                return c;
            }
        }
         */
        Dog dog = new Dog();
        Scanner scanner  = new Scanner(System.in);
        System.out.println("input a key");
        String key = scanner.next();
        switch (key){
            case "1":          //提前预先加载好这个类
                new Dog();//静态类加载,编译的时候就会判断是否有Dog这个类,如果没有就会报错.
                break;
            case "2":
                System.out.println("ni hao");
                break;
            case "3":                         //执行到这个地方的时候才会加载这个类
                Class cls = Class.forName("Person");//动态类加载,编译的时候不会检查报错
                Object o = cls.newInstance();
                Method m = cls.getMethod("hi");
                break;
            default :
                break;
        }
    }
}
class Dog{

}